package cn.wolfcode.service.impl;

import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.service.IOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Override
    @Transactional
    public String refund(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.select(orderNo);
        OperateIntergralVo vo = new OperateIntergralVo();
        vo.setPk(orderInfo.getOrderNo());
        vo.setUserId(orderInfo.getUserId());
        vo.setValue(orderInfo.getIntergral());
        vo.setInfo("退款操作");
        Message<OperateIntergralVo> message = MessageBuilder.withPayload(vo).build();
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction("tx_group","tx_topic",message,orderNo);
        String sendStatus = sendResult.getSendStatus().name();
        String localTXState = sendResult.getLocalTransactionState().name();
        log.info(">>>> send status={},localTransactionState={} <<<<",sendStatus,localTXState);
        return "退款成功";
    }
    
    @Transactional
    @Override
    public void changeOrderStatus(String orderNo) {
       orderInfoMapper.changeRefundStatus(orderNo,OrderInfo.STATUS_REFUND);
    }
    
    @Override
    public Integer getOrderStatus(String orderNo) {

        return orderInfoMapper.select(orderNo).getStatus();
    }
}
